<template>
  <div class="ai-chat">
    <!-- 头部导航 -->
    <van-nav-bar
      title="AI购物助手"
      left-arrow
      @click-left="handleBack"
      class="chat-header"
    >
      <template #right>
        <van-icon name="more-o" @click="showMenu = true" />
      </template>
    </van-nav-bar>

    <!-- 聊天内容区域 -->
    <div class="chat-content" ref="chatContentRef">
      <div class="chat-messages">
        <!-- 欢迎消息 -->
        <div v-if="messages.length === 0" class="welcome-message">
          <div class="welcome-avatar">
            <svg viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2ZM21 9V7L15 1H5C3.9 1 3 1.9 3 3V7C3 8.1 3.9 9 5 9H8V11C8 12.1 8.9 13 10 13H14C15.1 13 16 12.1 16 11V9H19C20.1 9 21 8.1 21 7V9Z"/>
            </svg>
          </div>
          <div class="welcome-content">
            <h3>你好！我是AI购物助手</h3>
            <p>我可以帮你：</p>
            <ul>
              <li>🔍 搜索商品</li>
              <li>💡 推荐商品</li>
              <li>📋 比较商品</li>
              <li>🛒 快速下单</li>
            </ul>
            <p>试试问我："推荐一些手机"或"有什么优惠商品"</p>
          </div>
        </div>

        <!-- 聊天消息列表 -->
        <ChatMessage
          v-for="message in messages"
          :key="message.id"
          :message="message"
          @product-click="handleProductClick"
          @buy-product="handleBuyProduct"
        />
      </div>
    </div>

    <!-- 快捷回复 -->
    <div v-if="quickReplies.length > 0" class="quick-replies">
      <div class="quick-replies-title">快捷回复：</div>
      <div class="quick-replies-list">
        <van-button
          v-for="reply in quickReplies"
          :key="reply"
          type="default"
          size="small"
          @click="handleQuickReply(reply)"
          class="quick-reply-btn"
        >
          {{ reply }}
        </van-button>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <div class="input-container">
        <van-field
          v-model="inputMessage"
          placeholder="输入消息..."
          @keyup.enter="handleSend"
          class="message-input"
        >
          <template #button>
            <van-button
              type="primary"
              size="small"
              @click="handleSend"
              :loading="sending"
              :disabled="!inputMessage.trim()"
              class="send-btn"
            >
              发送
            </van-button>
          </template>
        </van-field>
      </div>
    </div>

    <!-- 菜单弹窗 -->
    <van-action-sheet
      v-model:show="showMenu"
      :actions="menuActions"
      @select="handleMenuSelect"
      cancel-text="取消"
    />

    <!-- 商品详情弹窗 -->
    <van-popup
      v-model:show="showProductDetail"
      position="bottom"
      :style="{ height: '70%' }"
      round
    >
      <div v-if="selectedProduct" class="product-detail-popup">
        <div class="popup-header">
          <h3>商品详情</h3>
          <van-icon name="cross" @click="showProductDetail = false" />
        </div>
        <div class="popup-content">
          <img :src="selectedProduct.image" :alt="selectedProduct.name" />
          <h4>{{ selectedProduct.name }}</h4>
          <p>{{ selectedProduct.description }}</p>
          <div class="price">¥{{ selectedProduct.price.toFixed(2) }}</div>
          <van-button type="primary" block @click="handleBuyProduct(selectedProduct)">
            立即购买
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog, showConfirmDialog } from 'vant'
import ChatMessage, { type ChatMessage as ChatMessageType, type ProductItem } from '../components/ChatMessage.vue'
import { orderService, PaymentSDK, PaymentMethod, type OrderItem } from '@/services/orderService'
import { aiService, type AIResponse } from '@/services/aiService'

const router = useRouter()

// 响应式数据
const messages = ref<ChatMessageType[]>([])
const inputMessage = ref('')
const sending = ref(false)
const showMenu = ref(false)
const showProductDetail = ref(false)
const selectedProduct = ref<ProductItem | null>(null)
const chatContentRef = ref<HTMLElement>()

const quickReplies = ref([
  '推荐手机',
  '优惠商品',
  '热销商品',
  '数码产品'
])

const menuActions = [
  { name: '清空聊天记录', value: 'clear' },
  { name: '常见问题', value: 'faq' },
  { name: '联系客服', value: 'contact' }
]

// 模拟商品数据
const mockProducts: ProductItem[] = [
  {
    id: '1',
    name: 'iPhone 15 Pro Max',
    price: 9999,
    originalPrice: 10999,
    image: 'https://picsum.photos/200/200?random=1',
    description: '最新款iPhone，性能强劲',
    rating: 4.8,
    sales: 15000
  },
  {
    id: '2',
    name: 'MacBook Pro 14英寸',
    price: 15999,
    originalPrice: 17999,
    image: 'https://picsum.photos/200/200?random=2',
    description: 'M3芯片，专业级性能',
    rating: 4.9,
    sales: 8500
  },
  {
    id: '3',
    name: 'AirPods Pro 2',
    price: 1899,
    originalPrice: 2199,
    image: 'https://picsum.photos/200/200?random=3',
    description: '主动降噪，音质出色',
    rating: 4.7,
    sales: 25000
  }
]

// 方法
function handleBack(): void {
  router.back()
}

async function handleSend(): Promise<void> {
  if (!inputMessage.value.trim() || sending.value) return

  const userMessage = inputMessage.value.trim()
  inputMessage.value = ''
  sending.value = true

  // 添加用户消息
  const userMsg: ChatMessageType = {
    id: Date.now().toString(),
    type: 'user',
    content: userMessage,
    timestamp: Date.now()
  }
  messages.value.push(userMsg)

  // 滚动到底部
  await scrollToBottom()

  // 添加AI思考中的消息
  const loadingMsg: ChatMessageType = {
    id: (Date.now() + 1).toString(),
    type: 'bot',
    loading: true,
    timestamp: Date.now()
  }
  messages.value.push(loadingMsg)
  await scrollToBottom()

  try {
    // 模拟AI回复
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 移除加载消息
    messages.value = messages.value.filter(msg => msg.id !== loadingMsg.id)
    
    // 生成AI回复
    const aiResponse = await generateAIResponse(userMessage)
    messages.value.push(aiResponse)
    
    await scrollToBottom()
  } catch (error) {
    console.error('发送消息失败:', error)
    showToast('发送失败，请重试')
    // 移除加载消息
    messages.value = messages.value.filter(msg => msg.id !== loadingMsg.id)
  } finally {
    sending.value = false
  }
}

async function generateAIResponse(userMessage: string): Promise<ChatMessageType> {
  try {
    // 使用AI服务生成回复
    const aiResponse: AIResponse = await aiService.generateResponse(userMessage)
    
    // 转换AI服务的商品格式到组件需要的格式
    const products = aiResponse.products?.map(product => ({
      id: product.id,
      name: product.name,
      price: product.price,
      originalPrice: product.originalPrice,
      image: product.image,
      description: product.description,
      rating: product.rating,
      sales: product.sales
    }))
    
    return {
      id: Date.now().toString(),
      type: 'bot',
      content: aiResponse.text,
      products: products || undefined,
      timestamp: Date.now()
    }
  } catch (error) {
    console.error('AI回复生成失败:', error)
    
    // 降级处理 - 使用原有的简单逻辑
    const message = userMessage.toLowerCase()
    
    if (message.includes('手机') || message.includes('iphone')) {
      return {
        id: Date.now().toString(),
        type: 'bot',
        content: '为您推荐以下热门手机产品：',
        products: [mockProducts[0]],
        timestamp: Date.now()
      }
    } else if (message.includes('电脑') || message.includes('笔记本') || message.includes('macbook')) {
      return {
        id: Date.now().toString(),
        type: 'bot',
        content: '为您推荐以下电脑产品：',
        products: [mockProducts[1]],
        timestamp: Date.now()
      }
    } else {
      return {
        id: Date.now().toString(),
        type: 'bot',
        content: '抱歉，我现在有点忙，请稍后再试。如果您有紧急需求，可以直接浏览我们的商品分类。',
        timestamp: Date.now()
      }
    }
  }
}

function handleQuickReply(reply: string): void {
  inputMessage.value = reply
  handleSend()
}

function handleProductClick(product: ProductItem): void {
  selectedProduct.value = product
  showProductDetail.value = true
}

async function handleBuyProduct(product: ProductItem): Promise<void> {
  try {
    showToast.loading({
      message: '正在创建订单...',
      forbidClick: true,
      duration: 0
    })

    // 创建订单项
    const orderItem: OrderItem = {
      productId: product.id,
      productName: product.name,
      productImage: product.image,
      price: product.price,
      quantity: 1
    }

    // 创建订单
    const order = await orderService.createOrder([orderItem])
    
    showToast.clear()
    
    // 确认支付
    const confirmed = await showConfirmDialog({
      title: '确认支付',
      message: `确认购买 ${product.name}？\n价格：¥${product.price.toFixed(2)}\n订单号：${order.id}`
    })

    if (confirmed) {
      // 选择支付方式
      const paymentMethod = await showDialog({
        title: '选择支付方式',
        message: '请选择您的支付方式',
        showCancelButton: true,
        confirmButtonText: '微信支付',
        cancelButtonText: '支付宝'
      })

      showToast.loading({
        message: '支付中...',
        forbidClick: true,
        duration: 0
      })

      let paymentResult
      if (paymentMethod === 'confirm') {
        // 微信支付
        paymentResult = await PaymentSDK.wechatPay({
          orderId: order.id,
          method: PaymentMethod.WECHAT
        })
      } else {
        // 支付宝支付
        paymentResult = await PaymentSDK.alipay({
          orderId: order.id,
          method: PaymentMethod.ALIPAY
        })
      }
      
      showToast.clear()
      
      if (paymentResult.success) {
        showToast('支付成功！')
        
        // 关闭商品详情弹窗
        showProductDetail.value = false

        // 添加支付成功消息
        const successMsg: ChatMessageType = {
          id: Date.now().toString(),
          type: 'bot',
          content: `🎉 支付成功！\n订单号：${order.id}\n支付单号：${paymentResult.paymentId}\n我们会尽快为您发货，请注意查收。`,
          timestamp: Date.now()
        }
        messages.value.push(successMsg)
      } else {
        showToast(paymentResult.message)
        
        // 添加支付失败消息
        const failMsg: ChatMessageType = {
          id: Date.now().toString(),
          type: 'bot',
          content: `支付失败：${paymentResult.message}。您可以稍后重试或联系客服。`,
          timestamp: Date.now()
        }
        messages.value.push(failMsg)
      }
      
      await scrollToBottom()
    } else {
      // 取消支付，取消订单
      await orderService.cancelOrder(order.id)
      showToast('已取消购买')
    }
  } catch (error) {
    showToast.clear()
    showToast('操作失败，请重试')
    console.error('购买商品失败:', error)
  }
}



function handleMenuSelect(action: any): void {
  switch (action.value) {
    case 'clear':
      showConfirmDialog({
        title: '确认清空',
        message: '确定要清空所有聊天记录吗？'
      }).then(() => {
        messages.value = []
        showToast('聊天记录已清空')
      }).catch(() => {})
      break
    case 'faq':
      showDialog({
        title: '常见问题',
        message: '1. 如何搜索商品？\n直接输入商品名称即可\n\n2. 如何购买商品？\n点击推荐商品的"立即购买"按钮\n\n3. 支付安全吗？\n我们采用银行级加密技术'
      })
      break
    case 'contact':
      showDialog({
        title: '联系客服',
        message: '客服热线：400-123-4567\n在线时间：9:00-21:00\n邮箱：service@example.com'
      })
      break
  }
}

async function scrollToBottom(): Promise<void> {
  await nextTick()
  if (chatContentRef.value) {
    chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
  }
}

// 生命周期
onMounted(() => {
  // 初始化快捷回复
  setTimeout(() => {
    quickReplies.value = ['推荐手机', '优惠商品', '热销商品', '数码产品']
  }, 1000)
})
</script>

<style scoped>
.ai-chat {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  scroll-behavior: smooth;
}

.chat-messages {
  max-width: 100%;
}

.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 40px 20px;
  background: white;
  border-radius: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.welcome-avatar {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-bottom: 16px;
}

.welcome-avatar svg {
  width: 30px;
  height: 30px;
}

.welcome-content h3 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 18px;
}

.welcome-content p {
  margin: 8px 0;
  color: #666;
  font-size: 14px;
}

.welcome-content ul {
  text-align: left;
  margin: 12px 0;
  padding-left: 0;
  list-style: none;
}

.welcome-content li {
  margin: 6px 0;
  color: #666;
  font-size: 14px;
}

.quick-replies {
  padding: 12px 16px;
  background: white;
  border-top: 1px solid #f0f0f0;
}

.quick-replies-title {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.quick-replies-list {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.quick-reply-btn {
  height: 32px;
  font-size: 12px;
  border-radius: 16px;
  border: 1px solid #e0e0e0;
  background: #f8f9fa;
  color: #666;
}

.chat-input {
  background: white;
  border-top: 1px solid #f0f0f0;
  padding: 12px 16px;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.message-input {
  flex: 1;
}

.send-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 18px;
  height: 36px;
  padding: 0 16px;
}

.product-detail-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.popup-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.popup-content {
  flex: 1;
  padding: 20px;
  text-align: center;
}

.popup-content img {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border-radius: 12px;
  margin-bottom: 16px;
}

.popup-content h4 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #333;
}

.popup-content p {
  margin: 0 0 16px 0;
  color: #666;
  line-height: 1.5;
}

.popup-content .price {
  font-size: 24px;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-content {
    padding: 12px;
  }
  
  .welcome-message {
    padding: 30px 16px;
  }
  
  .welcome-avatar {
    width: 50px;
    height: 50px;
  }
  
  .welcome-avatar svg {
    width: 24px;
    height: 24px;
  }
  
  .popup-content img {
    width: 150px;
    height: 150px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .ai-chat {
    background: #1a1a1a;
  }
  
  .chat-input,
  .quick-replies {
    background: #2a2a2a;
    border-color: #404040;
  }
  
  .welcome-message {
    background: #2a2a2a;
  }
  
  .welcome-content h3 {
    color: #e0e0e0;
  }
  
  .welcome-content p,
  .welcome-content li {
    color: #b0b0b0;
  }
  
  .quick-reply-btn {
    background: #333;
    border-color: #555;
    color: #b0b0b0;
  }
  
  .popup-header {
    border-color: #404040;
  }
  
  .popup-header h3 {
    color: #e0e0e0;
  }
  
  .popup-content h4 {
    color: #e0e0e0;
  }
  
  .popup-content p {
    color: #b0b0b0;
  }
}
</style>